<template>
  <div class="close-icon">
    <div class="operation">
      <el-dropdown trigger="click">
        <el-icon color="#fffff">
          <ArrowDown />
        </el-icon>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="closeOtherPages"
              >关闭其他
            </el-dropdown-item>
            <el-dropdown-item @click="closeAllPages">全部关闭</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRoute } from 'vue-router'
import { useGlobalStore } from '@/store'
import { sessionCache } from '@/utils/cache'
import { TAB_LIST } from '@/global/constant'
import { storeToRefs } from 'pinia'
import router from '@/router'

const route = useRoute()
const globalStore = useGlobalStore()
const { tabList } = storeToRefs(globalStore)

// 关闭页面的类型
enum CloseType {
  ALL = 'all',
  Others = 'others'
}

// 关闭其他页面
const closeOtherPages = () => {
  closePages(CloseType.Others)
}
// 关闭全部页面
const closeAllPages = () => {
  closePages(CloseType.ALL)
}

// 封装一个方法关闭页面
function closePages(type: string) {
  // 1.找出当前索引
  const currentIndex = tabList.value.findIndex(
    (item) => item.path === route.path
  )
  // 2.修改数据
  const newTabList = tabList.value.filter((item, index) => {
    if (type === CloseType.Others) {
      return Number(index) === 0 || Number(index) === currentIndex
    } else {
      return Number(index) === 0
    }
  })
  tabList.value = newTabList
  // 3.本地也要更新
  sessionCache.setCache(TAB_LIST, newTabList)
  // 4.如果不是首页就关闭
  if (route.path !== '/dashboard' && type === CloseType.ALL) {
    router.push('/dashboard')
  }
}
</script>

<style scoped lang="less">
.close-icon {
  .operation {
    width: 34px;
    height: 34px;
    background-color: #ffff;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    margin-left: 20px;
  }
}
</style>
